package com.example.controller;

import com.example.bean.UserBean;
import com.example.model.ReturnNo;
import com.example.model.ReturnObject;
import com.example.service.UserService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "", produces = "application/json;charset=UTF-8")
public class LoginController {

    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public ReturnObject login(@RequestBody UserBean user) {
        if(null == user.getId() || null == user.getPassword()){
            logger.debug(user.toString());
            return new ReturnObject(ReturnNo.PARAMETER_MISSED);
        }
        UserBean userBean = userService.login(user.getId(), user.getPassword(), user.getIdentity());
        if (userBean != null) {
            logger.debug(userBean.toString());
            if (userBean.getId().equals(user.getId()) && userBean.getPassword().equals(user.getPassword())) {
                return new ReturnObject(ReturnNo.OK, "login successfully");
            }
        }
        return new ReturnObject(ReturnNo.AUTH_INVALID_ACCOUNT);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public ReturnObject register(@RequestBody UserBean user) {
        if (null == user.getName() || null == user.getPassword() || null == user.getPhone() || null == user.getEmail() || null == user.getIdentity()) {
            logger.debug(user.toString());
            return new ReturnObject(ReturnNo.PARAMETER_MISSED);
        }
        if(userService.judgePassword(user.getPassword()) && userService.judgePhone(user.getPhone()) && userService.judgeEmail(user.getEmail())){
            Long id = userService.register(user.getName(), user.getPassword(), user.getPhone(), user.getEmail(), user.getIdentity());
            if (null != id) return new ReturnObject(ReturnNo.CREATED, "注册成功", id);
        }
        return new ReturnObject(ReturnNo.AUTH_REGISTER_FAILED);
    }
}